<template>
  <el-dialog
    v-model="visible"
    title="版本比较"
    width="80%"
    :before-close="handleClose"
    destroy-on-close
    class="version-compare-dialog"
  >
    <!-- 版本选择区域 -->
    <div class="version-selector">
      <el-row :gutter="24">
        <el-col :span="11">
          <div class="version-select-section">
            <h4>源版本</h4>
            <el-select 
              v-model="sourceVersionId" 
              placeholder="请选择源版本"
              filterable
              clearable
              style="width: 100%"
              @change="handleSourceVersionChange"
            >
              <el-option
                v-for="version in availableVersions"
                :key="version.id"
                :label="`${version.version_number} - ${version.name}`"
                :value="version.id"
                :disabled="version.id === targetVersionId"
              >
                <div class="version-option">
                  <div class="version-info">
                    <span class="version-number">{{ version.version_number }}</span>
                    <span class="version-name">{{ version.name }}</span>
                  </div>
                  <VersionStatusTag :status="version.status" size="small" />
                </div>
              </el-option>
            </el-select>
          </div>
        </el-col>
        
        <el-col :span="2" class="compare-arrow">
          <el-icon><Right /></el-icon>
        </el-col>
        
        <el-col :span="11">
          <div class="version-select-section">
            <h4>目标版本</h4>
            <el-select 
              v-model="targetVersionId" 
              placeholder="请选择目标版本"
              filterable
              clearable
              style="width: 100%"
              @change="handleTargetVersionChange"
            >
              <el-option
                v-for="version in availableVersions"
                :key="version.id"
                :label="`${version.version_number} - ${version.name}`"
                :value="version.id"
                :disabled="version.id === sourceVersionId"
              >
                <div class="version-option">
                  <div class="version-info">
                    <span class="version-number">{{ version.version_number }}</span>
                    <span class="version-name">{{ version.name }}</span>
                  </div>
                  <VersionStatusTag :status="version.status" size="small" />
                </div>
              </el-option>
            </el-select>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 比较按钮 -->
    <div class="compare-actions">
      <el-button 
        type="primary" 
        @click="handleCompare" 
        :disabled="!sourceVersionId || !targetVersionId"
        :loading="comparing"
      >
        开始比较
      </el-button>
    </div>

    <!-- 比较结果 -->
    <div v-if="compareResult" class="compare-result">
      <!-- 比较概览 -->
      <el-card class="compare-overview">
        <template #header>
          <span>比较概览</span>
        </template>
        
        <el-row :gutter="16">
          <el-col :span="8">
            <div class="overview-item">
              <div class="overview-number added">+{{ compareResult.summary?.task_changes || 0 }}</div>
              <div class="overview-label">任务变更</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="overview-item">
              <div class="overview-number modified">{{ compareResult.summary?.defect_changes || 0 }}</div>
              <div class="overview-label">缺陷变更</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="overview-item">
              <div class="overview-number">{{ compareResult.summary?.total_changes || 0 }}</div>
              <div class="overview-label">总变更数</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 详细比较结果 -->
      <el-tabs v-model="activeTab" class="compare-tabs">
        <!-- 任务比较 -->
        <el-tab-pane label="任务变更" name="tasks">
          <el-collapse v-model="activeCollapse">
            <!-- 新增任务 -->
            <el-collapse-item 
              v-if="compareResult.task_differences?.added?.length > 0"
              title="新增任务" 
              name="added"
            >
              <template #title>
                <span>新增任务 ({{ compareResult.task_differences.added.length }})</span>
              </template>
              <div class="change-list">
                <div 
                  v-for="task in compareResult.task_differences.added" 
                  :key="task.id"
                  class="change-item added"
                >
                  <el-icon class="change-icon"><Plus /></el-icon>
                  <div class="change-content">
                    <div class="change-title">{{ task.entity_title }}</div>
                    <div class="change-meta">
                      <span>状态: {{ task.entity_status }}</span>
                      <span>关联时间: {{ formatDateTime(task.associated_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>

            <!-- 移除任务 -->
            <el-collapse-item 
              v-if="compareResult.task_differences?.removed?.length > 0"
              title="移除任务" 
              name="removed"
            >
              <template #title>
                <span>移除任务 ({{ compareResult.task_differences.removed.length }})</span>
              </template>
              <div class="change-list">
                <div 
                  v-for="task in compareResult.task_differences.removed" 
                  :key="task.id"
                  class="change-item removed"
                >
                  <el-icon class="change-icon"><Minus /></el-icon>
                  <div class="change-content">
                    <div class="change-title">{{ task.entity_title }}</div>
                    <div class="change-meta">
                      <span>状态: {{ task.entity_status }}</span>
                      <span>关联时间: {{ formatDateTime(task.associated_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>

            <!-- 修改任务 -->
            <el-collapse-item 
              v-if="compareResult.task_differences?.modified?.length > 0"
              title="修改任务" 
              name="modified"
            >
              <template #title>
                <span>修改任务 ({{ compareResult.task_differences.modified.length }})</span>
              </template>
              <div class="change-list">
                <div 
                  v-for="task in compareResult.task_differences.modified" 
                  :key="task.id"
                  class="change-item modified"
                >
                  <el-icon class="change-icon"><Edit /></el-icon>
                  <div class="change-content">
                    <div class="change-title">{{ task.entity_title }}</div>
                    <div class="change-meta">
                      <span>状态: {{ task.entity_status }}</span>
                      <span>关联时间: {{ formatDateTime(task.associated_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>

        <!-- 缺陷比较 -->
        <el-tab-pane label="缺陷变更" name="defects">
          <el-collapse v-model="activeCollapse">
            <!-- 新增缺陷 -->
            <el-collapse-item 
              v-if="compareResult.defect_differences?.added?.length > 0"
              title="新增缺陷" 
              name="added"
            >
              <template #title>
                <span>新增缺陷 ({{ compareResult.defect_differences.added.length }})</span>
              </template>
              <div class="change-list">
                <div 
                  v-for="defect in compareResult.defect_differences.added" 
                  :key="defect.id"
                  class="change-item added"
                >
                  <el-icon class="change-icon"><Plus /></el-icon>
                  <div class="change-content">
                    <div class="change-title">{{ defect.entity_title }}</div>
                    <div class="change-meta">
                      <span>状态: {{ defect.entity_status }}</span>
                      <span>关联时间: {{ formatDateTime(defect.associated_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>

            <!-- 移除缺陷 -->
            <el-collapse-item 
              v-if="compareResult.defect_differences?.removed?.length > 0"
              title="移除缺陷" 
              name="removed"
            >
              <template #title>
                <span>移除缺陷 ({{ compareResult.defect_differences.removed.length }})</span>
              </template>
              <div class="change-list">
                <div 
                  v-for="defect in compareResult.defect_differences.removed" 
                  :key="defect.id"
                  class="change-item removed"
                >
                  <el-icon class="change-icon"><Minus /></el-icon>
                  <div class="change-content">
                    <div class="change-title">{{ defect.entity_title }}</div>
                    <div class="change-meta">
                      <span>状态: {{ defect.entity_status }}</span>
                      <span>关联时间: {{ formatDateTime(defect.associated_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>

            <!-- 已解决缺陷 -->
            <el-collapse-item 
              v-if="compareResult.defect_differences?.resolved?.length > 0"
              title="已解决缺陷" 
              name="resolved"
            >
              <template #title>
                <span>已解决缺陷 ({{ compareResult.defect_differences.resolved.length }})</span>
              </template>
              <div class="change-list">
                <div 
                  v-for="defect in compareResult.defect_differences.resolved" 
                  :key="defect.id"
                  class="change-item resolved"
                >
                  <el-icon class="change-icon"><CircleCheck /></el-icon>
                  <div class="change-content">
                    <div class="change-title">{{ defect.entity_title }}</div>
                    <div class="change-meta">
                      <span>状态: {{ defect.entity_status }}</span>
                      <span>关联时间: {{ formatDateTime(defect.associated_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 空状态 -->
    <el-empty 
      v-if="!compareResult && !comparing" 
      description="请选择两个版本进行比较"
      :image-size="120"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button 
          v-if="compareResult" 
          type="primary" 
          @click="handleViewDetail"
        >
          查看详细比较
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Right,
  Plus,
  Minus,
  Edit,
  CircleCheck
} from '@element-plus/icons-vue'
import VersionStatusTag from './VersionStatusTag.vue'
import { versionAPI, type Version, type VersionComparison } from '@/api/version'
import { formatDateTime } from '@/utils/date'

// Props
interface Props {
  modelValue: boolean
  projectId?: string
  sourceVersion?: Version | null
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  projectId: '',
  sourceVersion: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

// Router
const router = useRouter()

// 响应式数据
const availableVersions = ref<Version[]>([])
const sourceVersionId = ref('')
const targetVersionId = ref('')
const compareResult = ref<VersionComparison | null>(null)
const comparing = ref(false)
const activeTab = ref('tasks')
const activeCollapse = ref(['added', 'modified', 'removed', 'resolved'])

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听器
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    loadVersions()
    // 如果传入了源版本，自动选择
    if (props.sourceVersion) {
      sourceVersionId.value = props.sourceVersion.id
    }
  } else {
    // 重置数据
    resetData()
  }
})

watch(() => props.sourceVersion, (newVal) => {
  if (newVal) {
    sourceVersionId.value = newVal.id
  }
})

// 生命周期
onMounted(() => {
  if (props.modelValue) {
    loadVersions()
  }
})

// 方法
const loadVersions = async () => {
  try {
    const params: any = {
      page: 1,
      size: 100
    }
    
    if (props.projectId) {
      params.project_id = props.projectId
    }
    
    const response = await versionAPI.getVersions(params)
    availableVersions.value = response?.data?.items || []
  } catch (error) {
    console.error('加载版本列表失败:', error)
    ElMessage.error('加载版本列表失败')
  }
}

const handleSourceVersionChange = (versionId: string) => {
  sourceVersionId.value = versionId
  // 清除之前的比较结果
  compareResult.value = null
}

const handleTargetVersionChange = (versionId: string) => {
  targetVersionId.value = versionId
  // 清除之前的比较结果
  compareResult.value = null
}

const handleCompare = async () => {
  if (!sourceVersionId.value || !targetVersionId.value) {
    ElMessage.warning('请选择两个版本进行比较')
    return
  }
  
  comparing.value = true
  try {
    const response = await versionAPI.compareVersions(
      sourceVersionId.value, 
      targetVersionId.value
    )
    compareResult.value = response
    ElMessage.success('版本比较完成')
  } catch (error) {
    console.error('版本比较失败:', error)
    ElMessage.error('版本比较失败')
  } finally {
    comparing.value = false
  }
}

const handleViewDetail = () => {
  // 跳转到详细比较页面
  router.push({
    path: '/versions/compare',
    query: {
      source: sourceVersionId.value,
      target: targetVersionId.value
    }
  })
  handleClose()
}

const handleClose = () => {
  visible.value = false
}

const resetData = () => {
  sourceVersionId.value = ''
  targetVersionId.value = ''
  compareResult.value = null
  comparing.value = false
  activeTab.value = 'tasks'
  activeCollapse.value = ['added', 'modified', 'removed', 'resolved']
}
</script>

<style scoped lang="scss">
.version-compare-dialog {
  .version-selector {
    margin-bottom: 20px;
    
    .version-select-section {
      h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
    
    .compare-arrow {
      display: flex;
      align-items: center;
      justify-content: center;
      padding-top: 32px;
      
      .el-icon {
        font-size: 20px;
        color: var(--el-color-primary);
      }
    }
  }
  
  .version-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    
    .version-info {
      display: flex;
      flex-direction: column;
      
      .version-number {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
      
      .version-name {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-top: 2px;
      }
    }
  }
  
  .compare-actions {
    text-align: center;
    margin: 20px 0;
  }
  
  .compare-result {
    margin-top: 20px;
    
    .compare-overview {
      margin-bottom: 20px;
      
      .overview-item {
        text-align: center;
        
        .overview-number {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 4px;
          
          &.added {
            color: var(--el-color-success);
          }
          
          &.modified {
            color: var(--el-color-warning);
          }
          
          &.removed {
            color: var(--el-color-danger);
          }
        }
        
        .overview-label {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }
    
    .compare-tabs {
      .change-list {
        .change-item {
          display: flex;
          align-items: flex-start;
          padding: 12px;
          margin-bottom: 8px;
          border-radius: 6px;
          border-left: 3px solid;
          
          &.added {
            background-color: var(--el-color-success-light-9);
            border-left-color: var(--el-color-success);
            
            .change-icon {
              color: var(--el-color-success);
            }
          }
          
          &.removed {
            background-color: var(--el-color-danger-light-9);
            border-left-color: var(--el-color-danger);
            
            .change-icon {
              color: var(--el-color-danger);
            }
          }
          
          &.modified {
            background-color: var(--el-color-warning-light-9);
            border-left-color: var(--el-color-warning);
            
            .change-icon {
              color: var(--el-color-warning);
            }
          }
          
          &.resolved {
            background-color: var(--el-color-info-light-9);
            border-left-color: var(--el-color-info);
            
            .change-icon {
              color: var(--el-color-info);
            }
          }
          
          .change-icon {
            margin-right: 12px;
            margin-top: 2px;
            font-size: 16px;
          }
          
          .change-content {
            flex: 1;
            
            .change-title {
              font-weight: 500;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
            }
            
            .change-meta {
              font-size: 12px;
              color: var(--el-text-color-secondary);
              
              span {
                margin-right: 16px;
              }
            }
          }
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}
</style>